package com.ruoyi;

import cn.hutool.core.util.RuntimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;

@Order(1)
@Component
@Slf4j
public class CommandLineRunnerImpl implements CommandLineRunner {

    @Value("${ray.video}")
    private String exePath;


    @Value("${ray.video_port}")
    private String video_port;


    @Override
    public void run(String... args) throws Exception {
        System.out.println("应用启动完成：执行CommandLineRunner方法完成资源初始化");
        int port = Integer.parseInt(this.video_port); // 你要检查的端口号
        String host = "localhost"; // 要检查的主机名或IP地址

        if (isPortAvailable(host, port)) {
            System.out.println("端口 " + port + " 在主机 " + host + " 上未被占用");
        } else {
            System.out.println("端口 " + port + " 在主机 " + host + " 上已被占用");
            endProgramUsingPort(host, port);
        }

        try {
            System.out.println("打开视频监控地址" + exePath);
            Runtime.getRuntime().exec(exePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean isPortAvailable(String host, int port) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(host, port), 2000);
            return false;
        } catch (IOException e) {
            return true;
        }
    }


    public void endProgramUsingPort(String host, int port) {
//        String command = "netstat -ano | findstr :<"+ String.valueOf(port) +"> > find.txt  \n" +
//                "taskkill /F /FI \"PID eq find.txt\"";
//        String command = "netstat -a -n -o | findstr :" + String.valueOf(port);
        String command = "netstat -a -n -o";
        String res = cmd(command);



        String[] split = res.split("\n");
        System.out.println("分割后长度：" + split.length);

//参数：被切分字符串，分隔符逗号，0表示无限制分片数，去除两边空格，忽略空白项
//        List<String> split = StrSpliter.split(res, ',', 0, true, true);
//        Arrays.stream(split).forEach(i -> System.out.println("元素为：" + i));
        String pid = null;
        for (String i:split){
            if(i.contains("0.0.0.0:"+port)){
                String[] 分割后的 = i.split(" ");
//                for (String p:分割后的){
//                    System.out.println("p = " + p);
//                }
                pid = 分割后的[分割后的.length-1];
                System.out.println("占用端口"+port+"pid:" + pid);
                break;
            }
        }
//        System.out.println("res = " + res);
        command = "taskkill /F /PID "+pid;
//        res = cmd(command);

//        RuntimeUtil.exec("taskkill /F /PID "+pid);

        System.out.println(res);

        try {
            // 执行操作系统的命令行工具
            Process process = Runtime.getRuntime().exec("taskkill /F /PID " + pid);

            // 读取命令行工具的输出结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待命令行工具执行完毕
            int exitCode = process.waitFor();
            System.out.println("命令行工具执行完毕，退出码：" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        // 在这里执行结束占用端口的程序的逻辑
        // 可以使用Java的ProcessBuilder或Runtime类来执行系统命令或脚本
        // 例如，使用ProcessBuilder或Runtime类执行以下命令来结束占用端口的程序：
        // "taskkill /F /PID <pid>" （在Windows上）或 "kill -9 <pid>" （在Linux或Mac上）


    }

    public String cmd(String command) {
        // 获取Runtime类的实例
        // 执行命令并获取输出结果
//        System.out.println("command:" + command);
        String line = RuntimeUtil.execForStr(command);

        return line;
    }
}
